<script setup lang="ts">
const timeOutStore = useMyTimeoutStore();
const examGauge = useMyExamGaugeStore();

const data = ref<ExamType | undefined>();
onBeforeMount(async () => {
  data.value = (await $fetch("/api/exam/join")).data;
  timeOutStore.setTimeOut(data.value.expire * 60, finishExam);
  examGauge.init(data.value.eid, data.value.question_count);
});
// 题目列表
const testpaper_questions = computed(() => {
  return data.value
    ? data.value.testpaper_questions.map((o) => {
      o.isTest = false;
      return o;
    })
    : [];
});
const postData = ref<ExamPayload>({
  eid: data.value?.eid ?? 0,
  answers: Array.from({ length: testpaper_questions.value.length }).map(
    (i, index) => {
      return {
        eiid: index,
        solve: "",
      };
    },
  ),
});
const router = useRouter();
const toast = useToast();
// 阻止切换其他页面
const disableBack = ref(true);
onBeforeRouteLeave((to, from, next) => {
  if (disableBack.value) {
    toast.add({
      title: "请先提交!",
      id: "4782",
      color: "yellow",
      icon: "i-heroicons-exclamation-circle",
    });
  }
  else {
    next();
  }
});
const finishBuffer = ref(true);
async function finishExam() {
  if (finishBuffer.value && !(examGauge.answer_num === examGauge.question_count)) {
    toast.add({
      title: "还有未填写的题目!",
      id: "4782",
      color: "yellow",
      icon: "i-heroicons-exclamation-circle",
    });
    finishBuffer.value = false
    return
  }
  examGauge.$reset();
  $fetch("/api/exam/fin", {
    method: "POST",
    body: postData.value,
  }).then(() => {
    console.log("post", postData.value.answers);
    console.log("finish Exam");
    disableBack.value = false;
    router.replace("/exam");
  })
}
definePageMeta({
  middleware: ["auth"],
  layout: "noaside",
});
</script>

<template>
  <!-- <p>{{ $route.name }}</p> -->
  <!-- <n-grid :x-gap="20"> -->
  <!-- <n-grid-item :span="18"> -->
  <UContainer class="flex flex-col">
    <template #header>
      <h3 class="text-center font-bold">
        {{ data?.title }}
      </h3>
      <UDivider />
      <p class="space-x-5 text-sm text-center">
        <span>题目总数：{{ data?.testpaper_questions.length }}</span>
        <span>总分数：{{ data?.total_score }}</span>
        <span>时间：{{ data?.expire }}分钟</span>
      </p>
      <!-- {{ timeOutStore.timeOutSec }} -->
    </template>

    <!-- 题目组件 -->
    <ExamPaperTestItem
      v-for="(item, index) in testpaper_questions"
      :id="`question_${item.eiid}`"
      :key="index"
      v-model="postData"
      :item="item"
      :index="index"
      :has-answer="examGauge.gauge[index]?.isTest || false"
      @change="
        () => {
          // handleUserValueChange(item, $event)
        }
      "
      @answer-test-item="
        () => {
          examGauge.answerThat(index);
        }"
    />
    <UDivider />
    <UButton class="flex-grow basis-10" @click="finishExam">
      提交
    </UButton>
    <!-- {{ postData }} -->
  </UContainer>
</template>
